﻿using System;
using biz.ritter.javapi.util;
using biz.ritter.javapi.lang;
using biz.ritter.javapi.lang.reflect;
using System.Runtime.CompilerServices;
using biz.ritter.javapi.lang.annotation;

namespace Nofs.Net.AnnotationDriver
{
   
public class ClassMethodCache {
	//@SuppressWarnings("unchecked")
	private Map<Class, bool> _hasMap;
	//@SuppressWarnings("unchecked")
	private Map<Class, LinkedList<Method>> _methodMap;
	private Class _annotationType;

	//@SuppressWarnings("unchecked")
	public ClassMethodCache(Class annotationType) {
		_annotationType = annotationType;
		_hasMap = new HashMap<Class, bool>();
        _methodMap = new HashMap<Class, LinkedList<Method>>();
	}

	public Method getCachedMethod(Class cls) {
		List<Method> methods = getCachedMethods(cls);
		return methods.size() > 0 ? methods.get(0) : null;
	}

    [MethodImpl(MethodImplOptions.Synchronized)]
	public LinkedList<Method> getCachedMethods(Class cls) {
        LinkedList<Method> methods = new LinkedList<Method>();
		if(_hasMap.containsKey(cls)) {
			if(_hasMap.get(cls)) {
				methods = _methodMap.get(cls);
			}
		} else {
			foreach(Method m in cls.getMethods()) {
				foreach(IAnnotation a in m.getAnnotations()) {
					if(a.annotationType().getClass() == _annotationType) {
						methods.add(m);
						break;
					}
				}
			}
			_hasMap.put(cls, methods.size() > 0);
			if(methods.size() > 0) {
				_methodMap.put(cls, methods);
			}
		}
		return methods;
	}
}
}
